package com.seven.ssa.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seven.ssa.common.CounterManager;
import com.seven.ssa.common.ErrorCode;

import com.seven.ssa.constant.CommonConstant;
import com.seven.ssa.exception.BusinessException;
import com.seven.ssa.model.dto.question.QuestionEsDTO;
import com.seven.ssa.model.dto.question.QuestionQueryRequest;
import com.seven.ssa.model.entity.Question;
import com.seven.ssa.model.entity.QuestionBankQuestion;
import com.seven.ssa.model.entity.User;
import com.seven.ssa.model.vo.QuestionVO;
import com.seven.ssa.service.QuestionBankQuestionService;
import com.seven.ssa.service.QuestionService;
import com.seven.ssa.mapper.QuestionMapper;
import com.seven.ssa.service.UserService;
import com.seven.ssa.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
* @author Dell
* @description 针对表【question(题目)】的数据库操作Service实现
* @createDate 2025-06-14 10:41:37
*/
@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question>
    implements QuestionService{

    @Resource
    private QuestionBankQuestionService questionBankQuestionService;
    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Resource
    private CounterManager counterManager;
    @Resource
    private UserService userService;

    /**
     * 通用的获取题目查询条件的方法
     * @param questionQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Question> getQueryWrapper(QuestionQueryRequest questionQueryRequest) {
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        if(questionQueryRequest == null) {
            return queryWrapper;
        }
        //多字段查询
        String searchText = questionQueryRequest.getSearchText();
        if(StringUtils.isNotBlank(searchText)) {
            queryWrapper.and(qw->qw.like("title",searchText).or().like("content",searchText));
        }
        //模糊查询
        String title = questionQueryRequest.getTitle();
        String content = questionQueryRequest.getContent();
        String answer = questionQueryRequest.getAnswer();
        queryWrapper.like(StringUtils.isNotBlank(title),"title",title);
        queryWrapper.like(StringUtils.isNotBlank(content),"content",content);
        queryWrapper.like(StringUtils.isNotBlank(answer),"answer",answer);
        //JSON查询
        List<String> tagList =questionQueryRequest.getTags();
        if(CollUtil.isNotEmpty(tagList)) {
            for(String tag : tagList) {
                queryWrapper.like("tags","\"" + tag + "\"");
            }
        }
        //精确查询
        Long id = questionQueryRequest.getId();
        queryWrapper.eq(ObjectUtils.isNotEmpty(id),"id", id);
        //排序规则
        String sortField = questionQueryRequest.getSortField();
        String sortOrder = questionQueryRequest.getSortOrder();
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),sortOrder.equals("ascend"),sortField);
        //返回queryWrapper
        return queryWrapper;
    }

    /**
     * 题目对象转题目封装类
     * @param question
     * @return
     */
    @Override
    public QuestionVO getQuestionVO(Question question) {
        return QuestionVO.objToVo(question);
    }

    /**
     * 根据题库id，或题库标题，获取题目列表
     * @param questionQueryRequest
     * @return
     */
    @Override
    public Page<Question> listQuestionByPage(QuestionQueryRequest questionQueryRequest){
        QueryWrapper<Question> queryWrapper = this.getQueryWrapper(questionQueryRequest);
        Long questionBankId = questionQueryRequest.getQuestionBankId();
        if(questionBankId != null) {
            // 查询该题库内的题目id，并转为lambdaQueryWrapper，再转为库目关系列表，
            LambdaQueryWrapper<QuestionBankQuestion> lambdaQueryWrapper = Wrappers.lambdaQuery(QuestionBankQuestion.class)
                            .select(QuestionBankQuestion::getQuestionId)//只查询题目id一个字段
                            .eq(QuestionBankQuestion::getQuestionBankId,questionBankId);//条件：题库id等于所给的
            List<QuestionBankQuestion> questionBankQuestionList =
                    questionBankQuestionService.list(lambdaQueryWrapper);
            if(CollUtil.isNotEmpty(questionBankQuestionList)) {
                //从库目关系列表中，取出题目id列表
                Set<Long> questionIdList = questionBankQuestionList.stream()
                        .map(QuestionBankQuestion::getQuestionId)
                        .collect(Collectors.toSet());
                //复用查询条件，以题目id列表中id作为查询条件
                queryWrapper.in("id", questionIdList);
            }
        }
        // 查询数据库
        long current = questionQueryRequest.getCurrent();
        long size = questionQueryRequest.getPageSize();
        return this.page(new Page<>(current,size),queryWrapper);
    }

    /**
     * 获取题目视图页
     *
     * @param questionPage
     * @param request
     * @return
     */
    @Override
    public Page<QuestionVO> getQuestionVOPage(Page<Question> questionPage, HttpServletRequest request) {
        // 通过题目页，获取题目列表
        List<Question> questionList = questionPage.getRecords();
        // 新建题目视图页
        Page<QuestionVO> questionVOPage = new Page<>(questionPage.getCurrent(), questionPage.getSize(), questionPage.getTotal());
        // 若题目列表为空，直接返回题目视图页
        if (CollUtil.isEmpty(questionList)) {
            return questionVOPage;
        }
        // 题目列表👉题目视图列表👉题目视图页
        List<QuestionVO> questionVOList = questionList.stream().map(QuestionVO::objToVo).collect(Collectors.toList());
        questionVOPage.setRecords(questionVOList);
        // 返回题目视图页
        return questionVOPage;
    }

    /**
     * P2：通过ES搜索题目
     * @param questionQueryRequest
     * @return
     */
    @Override
    public Page<Question> searchFromEs(QuestionQueryRequest questionQueryRequest){
        if(questionQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 限制爬虫
        if(questionQueryRequest.getPageSize()>200){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 新建布尔查询构造器
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // 过滤，只保留通过查询、符合要求的
        boolQueryBuilder.filter(QueryBuilders.termQuery("isDelete", 0));
        if(questionQueryRequest.getId() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("id", questionQueryRequest.getId()));
        }
        if(questionQueryRequest.getNotId() != null){
            boolQueryBuilder.filter(QueryBuilders.termQuery("id", questionQueryRequest.getNotId()));
        }
        if(questionQueryRequest.getUserId() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("userId", questionQueryRequest.getUserId()));
        }
        if(CollUtil.isNotEmpty(questionQueryRequest.getTags())) {
            for(String tag : questionQueryRequest.getTags()) {
                boolQueryBuilder.filter(QueryBuilders.termQuery("tags", tag));
            }
        }
        // 检索SearchText，只保留通过查询、符合要求的
        if(StringUtils.isNotBlank(questionQueryRequest.getSearchText())) {
            boolQueryBuilder.should(QueryBuilders.matchQuery("title", questionQueryRequest.getSearchText()));
            boolQueryBuilder.should(QueryBuilders.matchQuery("content", questionQueryRequest.getSearchText()));
            boolQueryBuilder.should(QueryBuilders.matchQuery("answer", questionQueryRequest.getSearchText()));
            boolQueryBuilder.minimumShouldMatch(1);
        }
        // 新建排序构造器，默认按文档的相关性评分降序排序
        SortBuilder<?> sortBuilder = SortBuilders.scoreSort();
        // 判断是否指定了排序字段SortField。如果指定了，就排序，并判断是升序还是降序
        if(StringUtils.isNotBlank(questionQueryRequest.getSortField())) {
            sortBuilder = SortBuilders.fieldSort(questionQueryRequest.getSortField());
            sortBuilder.order(CommonConstant.SORT_ORDER_ASC.equals(questionQueryRequest.getSortOrder())? SortOrder.ASC : SortOrder.DESC);
        }
        // 新建分页请求
        int current = questionQueryRequest.getCurrent() - 1; // 注意，ES 的起始页为 0
        int pageSize = questionQueryRequest.getPageSize();
        PageRequest pageRequest = PageRequest.of(current,pageSize);
        // 新建ES查询对象
        NativeSearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder)     // 设置查询主体，即上面的布尔查询构造器
                .withPageable(pageRequest)       // 设置分页参数，即上面的分页请求
                .withSorts(sortBuilder)          // 设置排序规则，即上面的排序构造器
                .build();
        // 调用elasticsearchRestTemplate当中的search方法，通过上面的ES查询对象，获取ES查询结果
        SearchHits<QuestionEsDTO> searchHits = elasticsearchRestTemplate.search(searchQuery, QuestionEsDTO.class);
        // 新建【答案列表】。若【ES查询结果】非空，则把【ES查询结果】转移到【ES查询结果列表中】，并把【ES查询结果列表】中结果转移到【答案列表】中
        List<Question> resourceList = new ArrayList<>();
        if(searchHits.hasSearchHits()) {
            List<SearchHit<QuestionEsDTO>> searchHitList = searchHits.getSearchHits();
            for (SearchHit<QuestionEsDTO> questionEsDTOSearchHit : searchHitList) {
                resourceList.add(QuestionEsDTO.dtoToObj(questionEsDTOSearchHit.getContent()));
            }
        }
        // 新建【分页对象】，设置【分页对象】大小，把【答案列表】中结果转移到【分页对象】中并返回。
        Page<Question> page = new Page<>();
        page.setTotal(searchHits.getTotalHits());
        page.setRecords(resourceList);
        return page;
    }


    /**
     * P6：检测爬虫
     *
     * @param loginUserId
     */
    @Override
    public void crawlerDetect(long loginUserId) {
        // 调用多少次时告警
        final int WARN_COUNT = 10;
        // 超过多少次封号
        final int BAN_COUNT = 20;
        // 拼接访问 key
        String key = String.format("user:access:%s", loginUserId);
        // 一分钟内访问次数，180 秒过期
        long count = counterManager.incrAndGetCounter(key, 1, TimeUnit.MINUTES, 180);
        // 是否封号
        if (count > BAN_COUNT) {
            // 踢下线
            StpUtil.kickout(loginUserId);
            // 封号
            User updateUser = new User();
            updateUser.setId(loginUserId);
            updateUser.setUserRole("ban");
            userService.updateById(updateUser);
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "访问太频繁，已被封号");
        }
        // 是否告警
        if (count == WARN_COUNT) {
            // 可以改为向管理员发送邮件通知
            throw new BusinessException(110, "警告访问太频繁");
        }
    }

}




